<script setup>
import { ref, onMounted, nextTick, computed } from "vue";
import Drawer from "@/components/Drawer.vue";
import AssetsList from "@/components/AssetsList.vue";
import {ElTable, ElTableColumn, ElMessage, ElTag} from "element-plus";
import {
  getLocationTree,
  getBorrowerPersonList,
  getDisposalList,
  addDisposal,
  getBorrowerDept,
  getDisposalDetail,
} from "@/api/AssetDisposal";

// 引入图标
import {Search, Refresh, Plus, View} from "@element-plus/icons-vue";

/***********资产处置表单数据******** */

// 新增资产处置弹框状态
const formVisible = ref(false);

// 资产处置表单实例对象
const formRef = ref(null);

// 资产处置弹框标题
const title = ref("");

// 资产处置表单数据
const disposalForm = ref({
  createTime: new Date().toISOString().split("T")[0], // 处置日期，默认今天
  type: "",
  reason: "",
  assets: [],
});

// 资产所在部门列表数据
const assetDept = ref([]);

// 处置后资产位置树形数据
const parentLocations = ref([]);

// 获取位置树形结构
const getLocationTreeData = () => {
  getLocationTree().then((res) => {
    if (res.code === 200) {
      parentLocations.value = res.data;
    }
  });
};

// 提交资产处置表单
const handleSubmit = () => {
  // 添加表单校验
  if (disposalForm.value.assets.length <= 0)
    return ElMessage.error("请选择资产");
  formRef.value.validate(async (valid) => {
    if (valid) {
      const { createTime, ...submitData } = disposalForm.value;
      addDisposal(submitData).then((res) => {
        if (res.code === 200) {
          ElMessage.success(`新增成功`);
          formVisible.value = false;
          // 调用子组件的取消选中方法
          assetsListRef.value?.clearSelection();
          resetForm();
          getDisposalAssetList();
        }
      });
    }
  });
};

// 资源借出列表数据
const disposalList = ref([]);

// 获取借出列表
const getDisposalAssetList = () => {
  getDisposalList().then((res) => {
    if (res.code === 200) {
      disposalList.value = res.data;
    }
  });
};

// 是否为编辑状态
const isEditMode = ref(false);

// 重置表单
const resetForm = () => {
  isEditMode.value = false;
  formRef.value?.resetFields();
  disposalForm.value = {
    createTime: new Date().toISOString().split("T")[0], // 处置日期，默认今天
    type: "",
    reason: "",
    assets: [],
  };
};

//点击处置按钮
const addDisposalData = () => {
  //重置表单 修改编辑状态
  resetForm();
  disposalForm.value.type = 1
  // 获取可处置资产
  // getAssetListData()
  //弹框显示
  formVisible.value = true;
  //弹框标题
  title.value = "新增资产处置";
};

// 处置人相关状态
const borrowPersonLoading = ref(false);
const borrowerPersonOptions = ref([]);

// 搜索处置人
const searchBorrowerPerson = async (query) => {
  if (query) {
    borrowPersonLoading.value = true;
    try {
      const res = await getBorrowerPersonList({ username: query });
      if (res.code === 200) {
        borrowerPersonOptions.value = res.data;
      }
    } finally {
      borrowPersonLoading.value = false;
    }
  } else {
    borrowerPersonOptions.value = [];
  }
};

// 处理处置人选择变化 获取选中的人的详细信息
const handleBorrowerChange = async (personId) => {
  console.log(personId, 7878);
  //处置人选择变化后 获取处置的username

  if (!personId) return;

  // 获取处置人详情
  const res = await getBorrowerDept(personId);
  if (res.code === 200) {
    // 自动填充部门信息
    assetDept.value = res.data.departments;
    // disposalForm.value.deptId = res.data.deptId;
  }
};

// 定义子组件 ref
const assetsListRef = ref(null);

// 点击取消关闭弹框
const handleCancel = () => {
  formVisible.value = false;
  // 调用子组件的取消选中方法
  assetsListRef.value?.clearSelection();
};

// 获取子组件选择处置的资产
const handleAssetSelect = (assetList) => {
  disposalForm.value.assets = assetList;
  console.log(assetList, 9999);
};

// 控制 Drawer 显示状态
const drawerVisible = ref(false);

// 点击编号时触发的方法
const handleClickTag = (id) => {
  // 给Drawer传递数据 打开 Drawer
  // 思路：点击编号时候，调用接口获取详情接口然后根据返回的数据组合成showFormData格式的数据
  getDisposalDetail({ id }).then((res) => {
    if (res.code === 200) {
      console.log(res, "详情数据");
      nextTick(() => {
        showFormData.value.orderNo = res.data.orderNo;
        showFormData.value.createTime = res.data.createTime;
        showFormData.value.type = res.data.type;
        showFormData.value.reason = res.data.reason;
        tableData.value = res.data.assets;
        console.log(formDataValues.value, 7777);
      });
    }
  });
  drawerVisible.value = true;
};

// 资产列表搜索框绑定的资产名称
const queryForm = ref({
  assetName: "",
});
// 根据资产名称查询处置列表
const handleBorrowSearch = () => {
  if (!queryForm.value.assetName) {
    ElMessage.warning("请输入资产名称");
    return;
  }
  const params = {
    orderNo: queryForm.value.assetName,
  };
  getDisposalList(params).then((res) => {
    if (res.code === 200) {
      disposalList.value = res.data;
    }
  });
};

// 重置资源处置列表数据
const handleBorrowReset = () => {
  queryForm.value.assetName = "";
  getDisposalAssetList();
};

const showFormData = ref({
  id: "",
  createTime: "",
  type: "",
  locationName: "",
  reason: "",
  assets: [],
});

const formDataValues = computed(() => [
  {
    label: "单据编号:",
    value: showFormData.value.orderNo,
  },

  {
    label: "资产状态:",
    value: showFormData.value.type == 0 ? "待处置" : "已处置",
  },
  {
    label: "处置类型:",
    value: showFormData.value.reason,
  },
  {
    label: "处置时间:",
    value: showFormData.value.createTime,
  },
]);

// tableData
const tableColumns = ref([
  {prop: "assetCode", label: "资产编码"},
  { prop: "name", label: "资产名称" },
  { prop: "categoryName", label: "资产分类" },
  { prop: "model", label: "型号规格" },
  // { prop: "serialNumber", label: "序列号" },
]);

const tableData = ref([]);

const drawerTitle = ref("资产处置详情");

// 关闭 Drawer 的方法
const closeDrawer = () => {
  drawerVisible.value = false;
};

const rules = {
  reason: [{ max: 200, message: "备注长度不能超过200个字符", trigger: "blur" }],
};

/*********** 页面加载时获取数据 *********/
onMounted(() => {
  //获取位置树数据
  getLocationTreeData();

  //获取借出列表数据
  getDisposalAssetList();
});
</script>

<template>
  <!-- 新增资产借出按钮与按资产名称搜索处置资源列表 -->

  <!-- 搜索框 -->
  <el-form
    :inline="true"
    :model="queryForm"
    class="demo-form-inline"
    style="margin-top: 10px"
  >
    <el-form-item>
      <el-space>
      <el-input
        v-model="queryForm.assetName"
        placeholder="请输入单据编号"
        clearable
        style="width: 300px"
        :prefix-icon="Search"
      >
        <template #append>
          <el-button type="primary" :icon="Search" style="background: #409eff;color: #ffffff;"
                     @click="handleBorrowSearch">
            搜索
          </el-button>
        </template>
      </el-input>
        <el-button type="primary" plain :icon="Refresh" @click="handleBorrowReset">重置</el-button>
        <!-- 新增按钮 -->
        <el-button plain type="primary" :icon="Plus" @click="addDisposalData">新增</el-button>
      </el-space>
    </el-form-item>
<!--    <el-form-item>
      &lt;!&ndash; 新增按钮 &ndash;&gt;
      <el-button plain type="primary" :icon="Plus" @click="addDisposalData">新增</el-button>
    </el-form-item>-->
  </el-form>
  <!------------ 新增资产处置弹框表单 ----------->
  <el-dialog
    v-model="formVisible"
    @close="handleCancel"
    close-on-click-modal="false"
    :title="title"
    width="70%"
  >
    <el-form
      :model="disposalForm"
      :rules="rules"
      ref="formRef"
      label-width="120px"
      inline
    >
      <el-form-item label="处置日期" prop="createTime">
        <el-date-picker
          v-model="disposalForm.createTime"
          disabled
          clearable
          type="date"
          placeholder="处置日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <!-- 处置类型下拉框，1-报废清理 2-盘亏处理 3-毁损清理 4-丢失 5-其他 -->
      <el-form-item label="处置类型" prop="type" style="width: 300px">
        <el-select
          v-model="disposalForm.type"
          placeholder="请选择处置类型"
          clearable
        >
          <el-option label="报废清理" :value="1" />
          <el-option label="盘亏处理" :value="2" />
          <el-option label="毁损清理" :value="3" />
          <el-option label="丢失" :value="4" />
          <el-option label="其他" :value="5" />
        </el-select>
      </el-form-item>

      <el-form-item label="处置说明" class="full-width">
        <el-input
          v-model="disposalForm.reason"
          type="textarea"
          :rows="3"
          clearable
          placeholder="请输入说明内容"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <!-- 资产列表 -->
      <AssetsList
        :status="0"
        ref="assetsListRef"
        @assetSelect="handleAssetSelect"
      />

      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-form>
  </el-dialog>

  <!-------------- 处置信息列表 --------------->
  <el-table
    :data="disposalList"
    table-layout="auto"
    height="80%"
    style="margin-top: 10px"
  >
    <!--    <el-table-column prop="id" label="处置id" align="center">-->
    <!--      <template #default="scope">-->
    <!--        <el-tag type="primary" @click="handleClickTag(scope.row.id)">{{-->
    <!--          scope.row.id-->
    <!--        }}</el-tag>-->
    <!--      </template>-->
    <!--    </el-table-column>-->
    <el-table-column prop="orderNo" label="单据编号" align="left"/>
<!--    <el-table-column prop="username" label="操作人" align="center"/>-->
    <el-table-column prop="status" label="资产状态" align="center">
      <template #default="scope">
        <el-tag
          color="#0ACF83"
          style="color: #fff"
          v-if="scope.row.status === 0"
          >待处置</el-tag
        >
        <el-tag type="success" v-if="scope.row.status === 1">已处置</el-tag>
        <el-tag type="warning" v-if="scope.row.status === 2">已取消</el-tag>
      </template>
    </el-table-column>
    <!--    处置类型 1-报废清理 2-盘亏处理 3-毁损清理 4-丢失 5-其他-->
    <el-table-column prop="type" label="处置类型" align="center">
      <template #default="scope">
        <el-tag v-if="scope.row.type === 1" type="primary">报废清理</el-tag>
        <el-tag v-else-if="scope.row.type === 2" type="danger">盘亏处理</el-tag>
        <el-tag v-else-if="scope.row.type === 3" type="danger">毁损清理</el-tag>
        <el-tag v-else-if="scope.row.type === 4" type="danger">丢失</el-tag>
        <el-tag v-else-if="scope.row.type === 5" type="warning">其他</el-tag>

        <el-tag v-else type="info">其他</el-tag>
      </template>
    </el-table-column>

    <el-table-column prop="reason" label="处置说明" align="center">
      <template #default="scope">
        <el-tooltip
          :content="scope.row.reason"
          placement="top"
          :disabled="!scope.row.reason || scope.row.reason.length <= 10"
        >
          <span class="table-cell-truncate">{{ scope.row.reason }}</span>
        </el-tooltip>
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="创建日期" align="center"/>
    <el-table-column label="操作" align="center" width="150">
      <template #default="scope">
        <el-link type="primary" :icon="View" @click="handleClickTag(scope.row.id)">查看</el-link>
      </template>
    </el-table-column>
  </el-table>

  <!--------------- 处置详情抽屉 ----------------->
  <Drawer
    v-model:visible="drawerVisible"
    :title="drawerTitle"
    :formData="showFormData"
    :formDataValues="formDataValues"
    :tableColumns="tableColumns"
    :tableData="tableData"
    @close="closeDrawer"
  />
</template>

<style scoped lang='less'>
.mb-4 {
  margin-bottom: 1rem;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

// 添加级联面板样式
:deep(.cascader-popper) {
  .el-cascader-node:not(.is-leaf) > .el-cascader-node__label {
    color: #409eff;
    &::after {
      content: "（可选）";
      font-size: 12px;
      color: #999;
    }
  }
}
.full-width {
  width: 100%;

  .el-textarea {
    width: 100%;
  }
}
.table-cell-truncate {
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px; /* 根据实际情况调整 */
}
</style>